// pages/recruitDynamics/index/index.js
import util from "../../../utils/util"
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    swiperData: [{
        id: 1,
        url: 'https://ws.dly.huikaoedu.com/upload/20220309/f4e47ffba5c9ff711e045cdcd8730b52.jpg',
      },
      {
        id: 2,
        url: 'https://ws.dly.huikaoedu.com/upload/20220309/2d1ce130249b9d1fedb7f9016d90d7d7.jpg',
      },
      {
        id: 3,
        url: 'https://ws.dly.huikaoedu.com/upload/20220309/bf1422f9b33df44712d1d0ee9c2871ed.jpg',
      },
      {
        id: 4,
        url: 'https://ws.dly.huikaoedu.com/upload/20220309/b1a6a8385f0569815c27a3064616df8f.gif',
      },
      {
        id: 5,
        url: 'https://ws.dly.huikaoedu.com/upload/20220309/735661e5181e483d00e1722b9ef8120d.jpg',
      },
    ],
    activeId: 1,
    bigData: {
      areaPop: false,
      timeLimit: '本月',
      areas: [
        '番禺区', '越秀区', '天河区', '南沙区', '海珠猪猪猪区'
      ],
      nowArea: '不限',
      areaPop: false,
      nowCity: '广州',
      alerts: {
        authorized: 0,
        unauthorized: 0,
        else: 0
      },
      highNeed: {
        '高中物理老师': 0,
        '小学数学老师': 0
      },
      highNeedNull: false,
      newTopic: 0,
      newPosition: 0
    },
    header: ['招教公告', '通知公示', '新闻资讯', '政策动态'],
    gzhPost: [],
    inf: [],
    state: ['即将报名', '正在报名', '结束报名'],
    publish: [],
    news: [],
    policy: []

  },
  setBackgroundPos() {
    // 蓝湖蒙层的top=104rpx==52px,背景高度=导航高度+512rpx
    const query = wx.createSelectorQuery();
    query.select('#navigationBar').boundingClientRect();
    query.exec((res) => {
      const {
        height
      } = res[0];
      this.setData({
        bgHeight: height + 256,
        backTop: height + 52
      });
    });
  },
  go2page(e) {
    this.selectComponent('#navigationBar').go2page(e);
  },
  toGzhPost(e) {
    wx.navigateTo({
      url: '../gzhWebView/gzhWebView?path=' + util.baseEncode(e.currentTarget.dataset.link),
    })
  },
  go_detail(e) {
    let k = e.currentTarget.dataset.index;
    console.log(this.data.inf[k]._id)
    wx.navigateTo({
      url: '../publishList_detail/1?_id=' + this.data.inf[k]._id,
    })
  },
  go_notice_detail(e) {
    let k = e.currentTarget.dataset.index;
    console.log(this.data.publish[k]._id)
    wx.navigateTo({
      url: '../Notice_detail/Notice_detail?_id=' + this.data.publish[k]._id,
    })
  },
  go_news_detail(e) {
    let k = e.currentTarget.dataset.index;
    console.log(this.data.news[k]._id)
    wx.navigateTo({
      url: '../news_detail/news_detail?_id=' + this.data.news[k]._id,
    })
  },
  go_policy_detail(e) {
    let k = e.currentTarget.dataset.index;
    wx.navigateTo({
      url: '../policy_detail/policy_detail?_id=' + this.data.policy[k]._id,
    })
  },
  updateBigData() {
    app.initCloudFunction().then(cloud => {
      cloud.callFunction({
        name: 'return-recruit-info',
        data: {
          action: 'show',
          choosetime: {
            '本月': 30,
            '本季': 30 * 3,
            '本年': 30 * 12
          } [this.data.bigData.timeLimit],
          city: this.data.bigData.nowCity + '市',
          district: this.data.bigData.nowArea
        },
        success: res => {
          var result = res.result
          var alertsData = {
            authorized: 0,
            unauthorized: 0,
            else: 0
          }
          for (let i = 0; i < result.authorized.length; i++) {
            const element = result.authorized[i]
            switch (element._id) {
              case 0:
                alertsData.authorized += element.total
                break
              case 1:
                alertsData.unauthorized += element.total
                break
              default:
                alertsData.else += element.total
                break
            }
          }
          var highNeedData = {}
          for (let i = 0; i < Math.min(result.needs.length, 2); i++)
            highNeedData[result.needs[i]._id] = result.needs[i].count
          this.setData({
            'bigData.alerts': alertsData,
            'bigData.highNeed': highNeedData,
            'bigData.highNeedNull': Object.keys(highNeedData) == 0,
            'bigData.newPosition': (result.newadd[0] || {
              total: 0
            }).total,
          })
        }
      })

      cloud.callFunction({
        name: 'getIndexInfo',
        data: {
          sign: 6,
          flag: {
            '本月': 2,
            '本季': 1,
            '本年': 0
          } [this.data.bigData.timeLimit],
          city: this.data.bigData.nowCity + '市',
          district: this.data.bigData.nowArea
        },
        success: res => {
          this.setData({
            'bigData.newTopic': res.result.count
          })
        }
      })
    })

  },
  openAreaPop() {
    this.setData({
      'bigData.areaPop': true
    })
  },
  closeAreaPop() {
    this.setData({
      'bigData.areaPop': false
    })
  },
  moreArea() {
    if (this.data.bigData.areaPop)
      this.closeAreaPop()
    else
      this.openAreaPop()
  },
  queryAreas(cityName) {
    app.initCloudFunction().then(cloud => {
      cloud.callFunction({
        name: 'getCityInf',
        data: {
          action: 'getAreas',
          cityName: cityName
        },
        success: res => {
          if (res.result.data.length > 0)
            this.setData({
              'bigData.areas': res.result.data[0].area,
              'bigData.areaNow': res.result.data[0].area[0]
            })
        }
      })
    })

  },
  areaChange(e) {
    this.setData({
      'bigData.nowArea': e.target.dataset.title
    })
    this.updateBigData()
  },
  areaPopClick(e) {
    this.setData({
      'bigData.nowArea': e.target.dataset.value
    })
    this.closeAreaPop()
    this.updateBigData()
  },
  timeLimitChange(e) {
    this.setData({
      'bigData.timeLimit': ['本月', '本季', '本年'][e.detail.value]
    })
    this.updateBigData()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      'bigData.nowCity': app.globalData.currentPos.city.split('市')[0]
    })
    this.selectComponent('#navigationBar').getMenuButtonRect();
    this.setBackgroundPos();
    this.queryAreas(this.data.bigData.nowCity)
    this.updateBigData()

    app.initCloudFunction().then(cloud => {
      cloud.callFunction({
        name: 'getGZH',
        data: {
          Action: 'getList',
          skip: 0,
          size: 3,
        },
        success: r => {
          this.setData({
            gzhPost: r.result.data
          })
        }
      })
      //引入招教公告信息
      cloud.callFunction({
        name: 'getIndexInfo',
        data: {
          sign: 0
        }
      }).then(res => {
        let ans = res.result.data;
        let k = {};
        let end = [];
        for (let i = 0; i < ans.length; i++) {
          k.tit = ans[i].title;
          k.begintime = util.formatTime(new Date(ans[i].StartTime));
          k.endtime = util.formatTime(new Date(ans[i].EndTime));
          k.unit = ans[i].apart;
          k.publishtime = util.formatTime(new Date(ans[i].date));
          k.state = ans[i].status;
          k._id = ans[i]._id;
          end.push(k);
          k = {};
        }
        this.setData({
          inf: end
        })
      })
      //通知公示数据载入
      cloud.callFunction({
          name: 'getIndexInfo',
          data: {
            sign: 1
          }
        }).then(res => {
          let ans = res.result.data;
          console.log(ans);
          let k = {};
          let end = [];
          for (let i = 0; i < ans.length; i++) {
            k.tit = ans[i].title;
            k.publishtime = util.formatTime(new Date(ans[i].date));
            k.unit = ans[i].apart;
            k._id = ans[i]._id;
            end.push(k);
            k = {};
          }
          this.setData({
            publish: end
          })
        }),
        //新闻资讯数据载入
        cloud.callFunction({
          name: 'getIndexInfo',
          data: {
            sign: 2
          }
        }).then(res => {
          let ans = res.result.data;
          let k = {};
          let end = [];
          for (let i = 0; i < ans.length; i++) {
            k.tit = ans[i].title;
            k.time = util.formatTime(new Date(ans[i].date));
            k.imageurl = ans[i].picture;
            k.unit = ans[i].apart;
            k._id = ans[i]._id;
            end.push(k);
            k = {};
          }
          this.setData({
            news: end
          })
          console.log("news-----------------:", this.data.news)
        }),
        //政策动态数据载入
        cloud.callFunction({
          name: 'getIndexInfo',
          data: {
            sign: 3
          }
        }).then(res => {
          let ans = res.result.data;
          let k = {};
          let end = [];
          for (let i = 0; i < ans.length; i++) {
            k.tit = ans[i].title;
            k.time = util.formatTime(new Date(ans[i].date));
            k.imageurl = ans[i].picture;
            k.unit = ans[i].apart;
            k._id = ans[i]._id;
            end.push(k);
            k = {};
          }
          this.setData({
            policy: end
          })
        })
    })
  },

  // 页面跳转
  go_more_posts() {
    const that = this
    var province = this.data.bigData.nowArea
    var city = this.data.bigData.nowCity
    if (province == undefined) {
      province = "广东省"
    }
    if (city == undefined) {
      city = "广州市"
    }
    console.log("url:", '../more_posts/more_posts?province=' + province + "&city=" + city)
    wx.$go2('../more_posts/more_posts?province=' + province + "&city=" + city, false)
  },
  JumpToMoreNews(e) {
    const targetPageType = e.currentTarget.dataset.type;
    if (getApp().globalData.isLogin == undefined) {
        wx.$cloud.callFunction({
            name: "inviteUser",
            data: {
                sign: 5
            },
            success: res => {
              wx.navigateTo({
                url: '/pages/recruitDynamics/new/more-news/more-news?type=' + targetPageType,
              })
                //如果该用户未登陆过
                // if (res.result.length == 0) {
                //     wx.showToast({
                //         title: '请先登录',
                //         icon: "error",
                //         duration: 1000
                //     })
                //     setTimeout(function () {
                //         wx.navigateTo({
                //             url: "/pages/login_main/login_main",
                //             success: (result) => {

                //             },
                //             fail: () => {},
                //             complete: () => {}
                //         });
                //     }, 1000)
                // } else {
                //     getApp().globalData.isLogin = true
                //     wx.navigateTo({
                //         url: '/pages/new/more-news/more-news?type=' + targetPageType,
                //     })
                // }
            }
        })
    } else {
        wx.navigateTo({
            url: '/pages/recruitDynamics/new/more-news/more-news?type=' + targetPageType,
        })
    }
  }, 
  JumpToRankList(e){
    const bigData = JSON.stringify(e.currentTarget.dataset.bigdata);
    const type = e.currentTarget.dataset.type
    wx.$go2('/pages/recruitDynamics/rankList/rankList?bigdata='+bigData+'&type='+type,false)
    //console.log(bigData)
  }

});